from datetime import time

class ScheduleOperations:
    def __init__(self, students, courses):
        self.students = students['students']
        self.courses = courses['courses']
    
    def check_conflicts(self, username):
        student = next((s for s in self.students if s['username'] == username), None)
        if not student:
            return "student not found"
    
        enrolled_courses = []
        for course_id in student['followed_courses']:
            course = next((c for c in self.courses if c['courseId'] == course_id), None)
            if course and 'schedule' in course:
                enrolled_courses.append({
                    'id': course_id,
                    'name': course.get('title', course_id),
                    'schedule': course['schedule']
                })
    
        conflict_messages = []
        for i in range(len(enrolled_courses)):
            for j in range(i+1, len(enrolled_courses)):
                if self._has_conflict(enrolled_courses[i]['schedule'], 
                    enrolled_courses[j]['schedule']):
                    conflict_messages.append(
                    f"------------------"
                    f"Identify conflicts:\n"
                    f"course1: {enrolled_courses[i]['name']} ({enrolled_courses[i]['id']})\n"
                    f"time: {enrolled_courses[i]['schedule'].get('days', [])} "
                    f"{enrolled_courses[i]['schedule'].get('time', '')}\n"
                    f"course2: {enrolled_courses[j]['name']} ({enrolled_courses[j]['id']})\n"
                    f"time: {enrolled_courses[j]['schedule'].get('days', [])} "
                    f"{enrolled_courses[j]['schedule'].get('time', '')}\n"
                    f"------------------"
                )
    
        return "\n".join(conflict_messages) if conflict_messages else "no course confliction"

    
    def _has_conflict(self, s1, s2):
        def parse_time(time_str):
            start_end = time_str.split('-')
            start = time(*map(int, start_end[0].split(':')))
            end = time(*map(int, start_end[1].split(':')))
            return start,end
        
        s1_start, s1_end = parse_time(s1['time'])
        s2_start, s2_end = parse_time(s2['time'])
        
        days_overlap = any(day in s2['days'] for day in s1['days'])
        time_overlap = not (s1_end <= s2_start or s2_end <= s1_start)
        
        return days_overlap and time_overlap
    
    
    def check_student_schedule_conflict(self, student, new_course):
        new_schedule = new_course['schedule']
        conflict_details = []
    
        for course_id in student['followed_courses']:
            existing_course = next((c for c in self.courses if c['courseId'] == course_id), None)
            if existing_course:
                conflict = self._get_conflict_detail(existing_course, new_course)
                if conflict:
                    conflict_details.append(conflict)
    
        return conflict_details if conflict_details else None
    
    def _get_conflict_detail(self, existing_course, new_course):
        existing_schedule = existing_course['schedule']
        new_schedule = new_course['schedule']

        if not self._has_conflict(existing_schedule, new_schedule):
            return None

        return {
            'existing_course': existing_course['courseId'],
            'existing_title': existing_course.get('title', ''),
            'existing_days': existing_schedule['days'],
            'existing_time': existing_schedule['time'],
            'new_course': new_course['courseId'],
            'new_days': new_schedule['days'],
            'new_time': new_schedule['time'],
            'conflict_days': list(set(existing_schedule['days']) & set(new_schedule['days']))
        }